#include <unistd.h>
#include <errno.h>
#include <limits.h>
#include <math.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include "utils.h"

const char *
Computer2HumanTime(int time)
{
  int minutes, hours, days;
  static char buffer[64];

  minutes=Dbl2Int(time/60.0);

  if(minutes>=60)
  {
    hours=minutes/60;
    minutes=minutes%60;

    if(hours>=24)
    {
      days=hours/24;
      hours=hours%24;
      sprintf(buffer, "%d days and %d hours", days, hours);
    }
    else
    {
      sprintf(buffer, "%d hours and %d minutes", hours, minutes);
    }
  }
  else
  {
    sprintf(buffer, "%d minutes", minutes);
  }

  return buffer;
}

int
Dbl2Int(double number)
{
  double temp;

  temp=floor(number+0.5);
  if(temp>INT_MAX)
  {
    temp=INT_MAX;
  }
  else if(temp<INT_MIN)
  {
    temp=INT_MIN;
  }
  return (int)temp;
}

int
MessageFormat(char **msg, const char *format, ...)
{
  int buffersize=256;
  int storedchars;

  *msg=NULL;
  do
  {
    char *buffer;
    va_list ap;

    buffer=realloc(*msg, buffersize*=2);
    if(!buffer)
    {
      free(*msg);
      errno=ENOMEM;
      return -1;
    }
    *msg=buffer;

    va_start(ap, format);
    storedchars=vsnprintf(buffer, buffersize, format, ap);
    va_end(ap);
  }
  while(storedchars==buffersize);
  return 0;
}
